/**
 * 
 */
package org.hotpotmaterial.codegenn2.config.security;

import org.hotpotmaterial.codegenn2.config.security.entrypoint.UnauthorizedEntryPoint;
import org.hotpotmaterial.codegenn2.config.security.filter.AuthenLogoutFilter;
import org.hotpotmaterial.codegenn2.config.security.filter.AuthenticationTokenFilter;
import org.hotpotmaterial.codegenn2.config.security.filter.LoginFilter;
import org.hotpotmaterial.codegenn2.config.security.provider.RegistUserProvider;
import org.hotpotmaterial.codegenn2.config.security.service.IAccountTokenService;
import org.hotpotmaterial.codegenn2.config.security.service.impl.AccountTokenServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author cakydeveloper
 *
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Bean
	public IAccountTokenService tokenService() {
		return new AccountTokenServiceImpl();
	}

	/**
	 * 资源中心认证登录
	 * 
	 * @return
	 */
	@Bean
	public RegistUserProvider regiestUserProvider() {
		RegistUserProvider rescenterUserProvider = new RegistUserProvider();
		return rescenterUserProvider;
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.cors().and().csrf().disable().authorizeRequests().antMatchers("/").permitAll().anyRequest().authenticated()
				.and().exceptionHandling().authenticationEntryPoint(new UnauthorizedEntryPoint()).and().formLogin()
				.loginProcessingUrl("/login").usernameParameter("username").passwordParameter("password").and().logout()
				.logoutUrl("/logout").addLogoutHandler(new AuthenLogoutFilter(tokenService())).and()
				.addFilterAt(new LoginFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class)
				.addFilter(new AuthenticationTokenFilter(authenticationManager(), tokenService()));
	}

	/**
	 * 登录配置
	 */
	@Override
	public void configure(AuthenticationManagerBuilder auth) throws Exception {
		// 可以添加多个
		auth.authenticationProvider(regiestUserProvider());
	}

	/**
	 * 忽略认证地址
	 */
	@Override
	public void configure(WebSecurity web) throws Exception {
		// ignore
		web.ignoring().antMatchers("/doc.html", "/v2/api-docs-ext", "/v2/api-docs", "/configuration/ui",
				"/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**", "/dist/**",
				"/actuator/**", "/hmteam/codegen/v1/accounts/register");
	}

}
